package controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import user.UserBean;
import utils.DateTimeUtils;
import utils.Picture;
import cameraConfig.Kamera;
import cameraConfig.KameraDAO;
import cameraConfig.Standort;

/**
 * @see Servlet implementation class PictureListController
 */
//@WebServlet(description = "Manages the picture list pages requests", urlPatterns = { "/PictureListController" })
public class PictureListController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PictureListController() {
        super();
    }
    
    private void process(HttpServletRequest request, HttpServletResponse response) {
    	ServletContext context;
		RequestDispatcher dispatcher;
		HttpSession session;
		
		context = getServletContext();
		session = request.getSession();
		
		String error = null;
		int errorCode = 0;
		
		String locationRequested = "";
		int[] camerasRequested = null;
		Date requestedFrom = null, requestedTo = null;
		
		UserBean curUser = (UserBean) (session.getAttribute("user"));
		Vector<Standort> locations = null;
		HashMap<String, Vector<Kamera>> locationCamerasMap = null;
		
		HashMap<Kamera, Vector<Picture>> picturesMap = null;
		
		KameraDAO camDoa = new KameraDAO();
		
		Map<String, String[]> parameters = request.getParameterMap();
		
		//check if a user is logged in
		if(curUser != null) {
			//extract from parameter and convert it to a date object
			if(request.getParameter("FromDateTime") != null) {
				requestedFrom = DateTimeUtils.parseDateTime(request.getParameter("FromDateTime"));
			}
			
			//extract to parameter and convert it to a date object
			if(request.getParameter("ToDateTime") != null) {
				requestedTo = DateTimeUtils.parseDateTime(request.getParameter("ToDateTime"));
			}
			
			locationRequested = curUser.getLocation();
			//check if the current user is marked as an administrator
			if(curUser.isAdmin()) {
				//user is an administrator and requested a special location
				if(request.getParameter("Location") != null)
					locationRequested = request.getParameter("Location");
				
				locations = camDoa.getLocations();
			} else {
				locations = new Vector<Standort>(1);
				locations.add(camDoa.getLocationByName(locationRequested));
			}
			
			//extract requested cameras parameter (depending on the current location)
			if(request.getParameter(locationRequested) != null) {
				try {
					String temp = request.getParameter(locationRequested);
					String[] camIdsAsString = temp.split(";");
					
					camerasRequested = new int[camIdsAsString.length];
					
					for(int i = 0; i < camIdsAsString.length; i++) {
						camerasRequested[i] = Integer.parseInt(camIdsAsString[i]);
					}
				} catch (Exception ex) {
					error = "Invalid format for camera ids passed";
					errorCode = 2;
					ex.printStackTrace();
				}
			}
			
			//load cameras for locations
			locationCamerasMap = new HashMap<String, Vector<Kamera>>();
			
			for(Standort location : locations) {
				Vector<Kamera> temp = camDoa.getCamObjectsIn(location);
				
				locationCamerasMap.put(location.getName(), KameraDAO.sortVectorByInactiv(temp, true));
			}
			
			try {
				//load requested pictures and build picture mapping
				
				HashMap<Integer, Vector<Picture>> temp = PictureControl.getInstance().SearchDatabaseForPictures(locationRequested, camerasRequested, requestedFrom, requestedTo);

				picturesMap = new HashMap<Kamera, Vector<Picture>>(temp.size());
				Vector<Kamera> locationsCams = locationCamerasMap.get(locationRequested);
				
				Kamera camTemp = null;
				for(Integer camID : temp.keySet()) {
					camTemp = KameraDAO.getKameraByIdFromVector(camID, locationsCams);
					
					if(camTemp != null)
						picturesMap.put(camTemp, temp.get(camID));
				}	
			} catch (Exception ex) {
				error = "Error allocating and scaling pictures";
				errorCode = 3;
				ex.printStackTrace();
			}
			
		} else {
			errorCode = 1;
			error = "User session expired";
		}
		
		//if an error occurred, do not pass any data
		if (error != null && !error.isEmpty()) {
			request.setAttribute("errorCode", errorCode);
			request.setAttribute("errorMessage", error);
		} else {
			//set all data the jsp has to render
			request.setAttribute("locations", locations);
			request.setAttribute("locationRequested", locationRequested);
			
			request.setAttribute("locationCamerasMap", locationCamerasMap);
			request.setAttribute("picturesMap", picturesMap);
			
			request.setAttribute("requestedFrom", request.getParameter("FromDateTime"));
			request.setAttribute("requestedTo", request.getParameter("ToDateTime"));
		}
		
		//pass the request to the picture list jsp
		dispatcher = context.getRequestDispatcher("/pictureListView.jsp");
				
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

}
